/**
 * 将字符串中的全角字符转换为半角字符。
 * @param {String} str 
 * @returns 
 */
function DBC2SBC(str)
{
    var result = "";
    for(var i = 0; i < str.length; i++)
    {
        code = str.charCodeAt(i);    //获取当前字符的unicode编码
        if (code >= 65281 && code <= 65373)   //在这个unicode编码范围中的是所有的英文字母已经各种字符
        {
            var d = str.charCodeAt(i) - 65248;
            result += String.fromCharCode(d);   //把全角字符的unicode编码转换为对应半角字符的unicode码
        }
        else if (code == 12288)//空格
        {
            var d = str.charCodeAt(i) - 12288 + 32;
            result += String.fromCharCode(d);
        }
        else
        {
            result += str.charAt(i);
        }
    }
    return result;
}

/**
 * 去除首尾空格符
 * @param {String} str 
 * @returns 
 */
function trimStr(str){
    return str.replace(/(^\s*)|(\s*$)/g,"");
}

var srcDataAddressX = 0
var srcDataAddressY = 0
var srcDataColumnsCount = 0
var srcDataRowsCount = 0
var srcSheetName = 0
var srcRange

var findAddressX = 0
var findAddressY = 0
var findRowsCount = 0  // 只支持一列查找
var findSheetName = 0
var findRange

var dataSourceWorkbook;
var findWorkbook;

function onbuttonclick(idStr)
{
    if (typeof (wps.Enum) != "object") { // 如果没有内置枚举值
        wps.Enum = WPS_Enum
    }
    switch(idStr)
    {
        case "setDataSource":{
                //alert("setDataSource")
                dataSourceWorkbook = wps.EtApplication().ActiveWorkbook;
                var aSheet = dataSourceWorkbook.ActiveSheet;
                srcSheetName = aSheet.Name;
                var txtDataSource = document.getElementById("txtDataSource");
                let s = wps.Application.Selection;
                if(s.Areas.Count != 1){
                    alert("用于查找的源数据区域必须是连续的！");
                    return;
                }
                var srcAddress = ("From: [" + dataSourceWorkbook.Name + "] - " + srcSheetName + "\r\nRow: " + s.Row + ", Rows Count: " + s.Rows.Count + "\r\n" +
                                  "Column: " + s.Column + ", Columns Count: " + s.Columns.Count);
                //alert(srcAddress)
                txtDataSource.value = srcAddress;
                srcRange = s;
                
                srcDataAddressY = s.Row;
                srcDataAddressX = s.Column;
                srcDataColumnsCount = s.Columns.Count;
                srcDataRowsCount = s.Rows.Count;

                break
            }
        case "setFindColumn":{              
                //alert("setFindColumn")
                findWorkbook = wps.EtApplication().ActiveWorkbook;
                var aSheet = findWorkbook.ActiveSheet;
                findSheetName = aSheet.Name;

                var findColumn = document.getElementById("txtFindColumn")
                let s = wps.Application.Selection
                if(s.Areas.Count != 1){
                    alert("用作查找条件的数据区域必须是连续的！");
                    return;
                }

                if(s.Rows.Count < 1){
                    alert("用作查找条件的数据区域不能少于1行！");  // 其实根本不可能少于1行
                    return;
                }

                var findColumnAddress = ("Find: [" + findWorkbook.Name + "] - " + findSheetName + "\r\nRow: " + s.Row + ", Rows Count: " + s.Rows.Count + "\r\n" +
                                  "Column: " + s.Column + ", Columns Count: " + s.Columns.Count );
                //alert(findColumnAddress)

                var conditionColIndexInput = document.getElementById('conditionColIndex');
                if(conditionColIndexInput){
                    conditionColIndexInput.value = s.Columns.Count;
                }
                findColumn.value = findColumnAddress

                findAddressX = s.Column;
                findAddressY = s.Row;
                findRowsCount = s.Rows.Count; 
                findColumnsCount = s.Columns.Count;
                findRange = s;
                break
            }
        case "btnHook":{
                //alert("abcd")
                var ckxSourceDataWithTitle = document.getElementById("ckxSourceDataWithTitle")
                var ckxFindWithTitle = document.getElementById("ckxFindWithTitle")

                if(dataSourceWorkbook == undefined){
                    alert("未设置数据源表！");
                    return;
                }
                if(findWorkbook == undefined){
                    alert("未设置查找条件表！");
                    return;
                }
                var srcSheets = dataSourceWorkbook.Sheets;                
                var srcSheet;
                for(j=1; j<=srcSheets.Count; j++){   // 注意：这个索引是从1开始的！！！
                    var ss = srcSheets.Item(j);
                    if(ss==null)continue;
                    if(ss.Name == srcSheetName){
                        srcSheet = ss;
                        break;
                    }
                }                
                if(srcSheet == undefined){
                    alert('未找到源数据表！');
                    return;
                }
                var findSheets = findWorkbook.Sheets;
                var fndSheet;
                for(j=1; j<=findSheets.Count; j++){   // 注意：这个索引是从1开始的！！！
                    var fs = findSheets.Item(j);
                    if(fs==null)continue;
                    if(fs.Name == findSheetName){
                        fndSheet = fs;
                        break;
                    }
                }
                if(fndSheet == undefined){
                    alert('未找到查找条件所在数据表！');
                    return;
                }

                var srcOffcet = 0;
                var fndOffcet = 0;

                // 注意:坐标是先行后列!!!不是先X后Y!!!
                var srcRange = srcSheet.Range(srcSheet.Cells.Item(srcDataAddressY + srcOffcet, srcDataAddressX), srcSheet.Cells.Item(srcDataAddressY + srcDataRowsCount - 1, srcDataAddressX + srcDataColumnsCount - 1));
                var srcArray = srcRange.Value2;
                var fndRange = fndSheet.Range(fndSheet.Cells.Item(findAddressY + fndOffcet, findAddressX), fndSheet.Cells.Item(findAddressY + findRowsCount - 1, findAddressX + findColumnsCount - 1));  // 注意：查找条件列暂时只支持一列
                var fndArray = fndRange.Value2;

                if(srcArray == null){
                    alert("指定的源数据区域中没有可用的数据!");
                    return;
                }

                let cellRows = Math.min(srcRange.Rows.Count, fndRange.Rows.Count);

                let hookedCellsCount = 0;
                let existDataCount = 0;
                for(i = 0; i < cellRows; i++) {  // 查找条件列中每行（这里只支持单列，即每个单元格）逐次循环
                    var fndValue = fndArray[i][0];
                    if(fndValue != null && fndValue != "")
                    {
                        existDataCount++;
                        continue;  // 如果已有数据，不再钩取新数据，防止误填。
                    } 

                    var v = srcArray[i][0];   // 数组从0开始算
                    if(v == null) continue;                // 查找条件中可能有空单元格（例如合并单元格做的表头）
                    v = trimStr(DBC2SBC(v.toString()));
                    
                    fndArray[i][0] = v;
                    hookedCellsCount++;
                }

                fndRange.Value2 = fndArray;
                var msg = `已钩取 ${hookedCellsCount} 个单元格！`; 
                if(existDataCount > 0){
                    msg += `有 ${existDataCount} 个单元格中已存在数据，为防止误覆盖，没有执行钩取操作。如果确实需要覆盖这些数据，请手动删除再执行本操作！`;
                }
                alert(msg);
                break;
            }
    }
}


window.onload = ()=>{
    // var xmlReq = WpsInvoke.CreateXHR();
    // var url = location.origin + "/.debugTemp/NotifyDemoUrl"
    // xmlReq.open("GET", url);
    // xmlReq.onload = function (res) {
    //     var node = document.getElementById("DemoSpan");
    //     window.document.getElementById("DemoSpan").innerHTML = res.target.responseText;
    // };
    // xmlReq.send();
}